package feeinterface.protocol.reqn;

import java.util.Map;

import org.apache.log4j.Logger;

import com.ulwx.tool.ObjectUtils;
import com.ulwx.tool.StringUtils;

import feeinterface.dao.BaseImsiPhoneDao;
import feeinterface.dao.MobileExtDao;
import feeinterface.modeldb.BaseImsiPhone;
import feeinterface.modeldb.MobileExt;
import feeinterface.protocol.req.Pro010001;
import feeinterface.protocol.req.Pro010005;
import feeinterface.protocol.req.ProExchange;

import feeinterface.protocol.res.ChannelIVR;
import feeinterface.protocol.res.ChannelSMS;
import feeinterface.protocol.res.ChannelWAP;
import feeinterface.protocol.res.ExtRespVar;

import feeinterface.protocol.res.Res010001;
import feeinterface.protocol.res.Res010005;
import feeinterface.protocol.resn.ChannelIvr;
import feeinterface.protocol.resn.ChannelSms;
import feeinterface.protocol.resn.ChannelWap;
import feeinterface.protocol.resn.FetchStep;
import feeinterface.protocol.resn.M201002;
import feeinterface.protocol.utils.Constants;
import feeinterface.utils.PhoneUtils;

public class T201002 extends ProExchange {
	private static Logger log = Logger.getLogger(T201002.class);

	public String Protocol;// string(6) 协议编号:：201002
	public Integer Ver;// int 扣费模块版本号，从0开始
	public Integer VmVer;// int 版本ID,两位，第一位为大版本号，第二位为小版本号，例如
							// 21，大版本号为2，小版本号为1，从10开始
	public Integer PacketID;// int 打包id。
	public Integer PlatformID;// int 见3平台id
	public String IMSI;// string(15) 手机卡串号
	public String SmsCenter;// string 短信中心号码
	public Integer SimType;// int 1:移动，2：联通，3：电信 4:网通
	public String Mobile;// String（22） 手机号码（如果为空，又由后台判断是否要发出获取手机号码协议请求（201001））
	public Integer Test; // int 0：真机 1：pc模拟器

	@Override
	public Object genBean() throws Exception {
		// TODO Auto-generated method stub

		this.IMSI = StringUtils.trim(this.IMSI);

		Pro010001 p = new Pro010001();
		p.setRequest(this.getRequest());
		p.CanSupport = "0";
		p.Carrier = 0;
		p.ChannelMaxNum = 0;
		p.COID = this.PacketID;
		p.ExtVar = "";
		p.FeeMode = 1;
		p.FeePolicy = "10000020"; // 在响应里不含有获取手机号码指令
		p.IMSI = this.IMSI;
		p.Mobile = this.Mobile;
		p.PacketID = this.PacketID + "";
		p.PayFee = 800;
		p.PhoneFactoryName = "";
		p.Platform = this.PlatformID + "";
		p.Protocol = "010001";
		p.QueryChannel = 0;
		p.RequestFrom = 1;
		p.SingleMaxFee = 0;
		p.SmsCenter = this.SmsCenter;
		p.Test = this.Test;
		p.Ver = this.Ver;
		p.VmVer = this.VmVer;

		Res010001 res = (Res010001) p.genBean();

		M201002 m = new M201002();
		// m.
		m.ExtRespVar = "";
		m.FeeID = res.FeeID;
		m.FeeStatus = res.FeeStatus;

		String accessNextDate = MonthFeeRequestDate.decideAccessDate(
				res.FeeStatus).substring(5);
		;

		// 获取销量统计信息
		m.IsNeedGetMobile = 0;
		boolean noGet = MonthFeeRequestDate.isNoGetPhone(res.FeeStatus);
		if (!noGet && this.IMSI != null
				&& "460".equals(this.IMSI.substring(0, 3))) {
			// IMSI正确，判断表中是否有手机号码，如果有，则不再获取。
			BaseImsiPhone bi = BaseImsiPhoneDao.getPhoneBy(IMSI);
			if (bi != null) {// 不需要客户端做销量统计
				m.IsNeedGetMobile = 0;
			} else { // 根据情况需要客户端作销量统计
				MobileExt met = null;
				try {
					met = MobileExtDao.getByIMSI(IMSI);
					if (met != null) {

						if (met.getDayGetPhoneCnt() > Constants.MobileLimit.PhoneGetDayMax
								|| met.getMonthGetPhoneCnt() > Constants.MobileLimit.PhoneGetMonthMax) { // 大于日限或月限
							m.IsNeedGetMobile = 0;
						} else {
							m.IsNeedGetMobile = 1;

						}
					} else {
						m.IsNeedGetMobile = 1;//
					}
				} catch (Exception e) {
					log.error("获取用户出错！", e);
				}

			}
		}

		ChannelSMS[] smss = res.sms;
		m.sms = new ChannelSms[smss.length];
		for (int i = 0; i < smss.length; i++) {
			ChannelSms temp = new ChannelSms();
			m.sms[i] = temp;
			temp.ChannelID = smss[i].ChannelID;
			temp.ExtSmsVar = "";
			temp.FeeTipInfo = "";
			temp.FeeType = smss[i].FeeType;
			temp.IsDouble = smss[i].IsDouble;
			temp.SendCnt = smss[i].SendCnt;
			temp.SendInterval = smss[i].SendInterval;
			temp.SmsEndFlag = smss[i].SmsEndFlag;
			temp.SmsFeeCmd = smss[i].SmsFeeCmd;
			temp.SmsFeeCode = smss[i].SmsFeeCode;
			temp.SmsFeePort = smss[i].SmsFeePort;
			temp.SmsStartFlag = smss[i].SmsStartFlag;
			temp.SmsValidateFlag = smss[i].SmsValidateFlag;
		}

		ChannelIVR[] ivrs = res.ivr;
		m.ivr = new ChannelIvr[ivrs.length];
		// 把ChannelIVR转换成ChannelIvr
		for (int i = 0; i < ivrs.length; i++) {
			ChannelIvr temp = new ChannelIvr();
			m.ivr[i] = temp;
			temp.ChannelID = ivrs[i].ChannelID;
			temp.ExtIvrVar = "";
			temp.FeeTipInfo = "";
			temp.FeeType = ivrs[i].FeeType;
			temp.IvrFeeTel = ivrs[i].IvrFeeTel;
			temp.KeySeries = ivrs[i].KeySeries;
			temp.SendCnt = ivrs[i].SendCnt;
			temp.SendInterval = ivrs[i].SendInterval;
		}

		ChannelWAP[] waps = res.wap;
		m.wap = new ChannelWap[waps.length];
		for (int i = 0; i < waps.length; i++) {
			ChannelWap temp = new ChannelWap();
			m.wap[i] = temp;
			temp.ChannelID = waps[i].ChannelID;
			temp.ExtWapVar = "";
			temp.FeeOKFlag = waps[i].FeeOKFlag;
			feeinterface.protocol.res.FetchStep[] oldFetchSteps = waps[i].FeeStep;
			FetchStep[] newFetchStep = new FetchStep[oldFetchSteps.length];
			for (int n = 0; n < oldFetchSteps.length; n++) {
				FetchStep fs = new FetchStep();
				newFetchStep[n] = fs;
				fs.EndKey = oldFetchSteps[n].EndKey;
				fs.FindKeys = oldFetchSteps[n].FindKeys;
			}
			temp.FeeStep = newFetchStep;
			temp.FeeTipInfo = "";
			temp.FeeType = waps[i].FeeType;
			temp.SendCnt = waps[i].SendCnt;
			temp.SendInterval = waps[i].SendInterval;
			temp.WapFeeUrl = waps[i].WapFeeUrl;
		}

		m.Message = res.Message;

		// 获得下次访问日期
		String respVar = res.ExtRespVar;
		try {
			if (StringUtils.hasText(respVar) && respVar.contains("{")&& respVar.contains("NextAccessDate")) {
				Map map = (Map) ObjectUtils.fromJsonToObject(respVar);
				String NextAccessDate = (String) map.get("NextAccessDate");
				if (StringUtils.hasText(NextAccessDate)) {
					m.NextDate = NextAccessDate;
				} else {
					m.NextDate = accessNextDate;
				}

				String mobile = (String) map.get("Mobile");
				if (StringUtils.hasText(mobile)) {
					m.Mobile = StringUtils.trim(mobile);
				} else {
					m.Mobile = "";
				}
			}else{
				m.NextDate = accessNextDate;
			}

			if (StringUtils.isEmpty(m.Mobile)) {
				m.Mobile = "";
			}
		} catch (Exception e) {
			log.error("", e);
		}

		m.SmsCloseKeyword = res.SmsCloseKeyword;
		m.SmsCloseMt = res.SmsCloseMt;
		m.SmsCloseSpNumber = res.SmsCloseSpNumber;
		m.SmsCloseTime = res.SmsCloseTime;
		m.SmsOpenSpNumber = res.SmsOpenSpNumber;
		m.Status = res.Status;
		m.ThisFee = res.ThisFee;

		return m;
	}

	@Override
	public String validate() throws Exception {
		// TODO Auto-generated method stub
		this.SmsCenter = PhoneUtils.getAdjustedPhone(this.SmsCenter);
		return null;
	}

}
